import {
	setItem,
	getItem,
	removeItem
} from "./storage.js";
import { handleCommunityData } from "@/base/common-business.js";

export const TOKEN_KEY = "TOKEN__";
export const AUTH_KEY = "AUTH_";
export const COMMUNITY_KEY = "COMMUNITY_";
export const REM_USER_INFO_KEY = "REMUSERINFO_";
export const USER_INFO_KEY = "USERINFO_";
const AGREE_KEY = "AGREE_";

function setAuthItem(key, value) {
	if (value === null) {
		removeItem(key);
	} else {
		setItem(key, value);
	}
}

const authCache = {
	token: null,
	remUserInfo: null,
	userInfo: null,
	agree: null,
	community: null,
	getToken() {
		return this.token || getItem(TOKEN_KEY);
	},
	getRemUserInfo() {
		if (this.remUserInfo) {
			return this.remUserInfo;
		}
		const userInfo = getItem(REM_USER_INFO_KEY, true);
		if (!userInfo) return null;
		this.remUserInfo = userInfo;
		return userInfo;
	},
	//获取用户详细信息
	getUserInfo() {
		if (this.userInfo) {
			return this.userInfo;
		}
		const userInfo = getItem(USER_INFO_KEY, true);
		this.userInfo = userInfo;
		return userInfo;
	},
	getCommunity(){
		if (this.community) {
			return this.community;
		}
		const community = getItem(COMMUNITY_KEY, true);
		this.community = community;
		return community;
	},
	getAgree(){
		if (this.agree) {
			return this.agree;
		}
		const val = getItem(AGREE_KEY);
		if (!val) return null;
		this.agree = val;
		return val;
	},
	setToken(token) {
		this.token = token;
		setAuthItem(TOKEN_KEY, token);
	},
	setRemUserInfo(userInfo) {
		if (!userInfo) {
			this.remUserInfo = null;
			setAuthItem(REM_USER_INFO_KEY, null);
			return;
		}
		this.remUserInfo = Object.assign({}, userInfo);
		setAuthItem(REM_USER_INFO_KEY, userInfo);
	},
	setUserInfo(userInfo) {
		this.userInfo = userInfo;
		setAuthItem(USER_INFO_KEY, userInfo);
	},
	setAgree(val){
		this.agree = val;
		setAuthItem(AGREE_KEY, val === null ? null : "1");
	},
	setCommunity(community) {
		this.community = community;
		setAuthItem(COMMUNITY_KEY, community);
	},
	clear() {
		this.setToken(null);
		this.setUserInfo(null);
		this.setCommunity(null);
		handleCommunityData(true);
	},
};
export default authCache;
